package com.wlient.demo.config;

import com.wlient.demo.service.mqtt.MqttCallbackService;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author: 史炜立
 * @description: TODO
 * @date: 2022/7/22 15:24
 */
@Configuration
public class mqttConfig {
    public String HOST = "ws://broker.emqx.io:8083"; //mqtt服务器的地址和端口号
    public String clientId = "DC" + (int) (Math.random() * 100000000);
    public String username = "admin";
    public  String passWord = "public";
    @Resource
    private MqttClient mqttClient;

    /**
     * MQTT连接参数设置
     */
    @Bean
    public MqttConnectOptions mqttConnectOptions() throws MqttException {
        mqttClient = new MqttClient(HOST, clientId, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(this.username);
        options.setPassword(this.passWord.toCharArray());
        options.setConnectionTimeout(10);//默认：30
        options.setAutomaticReconnect(true);//默认：false
        options.setCleanSession(false);//默认：true
        //options.setKeepAliveInterval(20);//默认：60
        mqttClient.setCallback(new MqttCallbackService());
        return options;
    }
}
